package com.hsl.study.controller;

import com.alibaba.cloud.ai.dashscope.agent.DashScopeAgent;
import com.alibaba.cloud.ai.dashscope.agent.DashScopeAgentOptions;
import com.alibaba.cloud.ai.dashscope.api.DashScopeAgentApi;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.Map;

/**
 * @auther zzyybs@126.com
 * @create 2025-08-01 16:51
 * @Description TODO
 */
@RestController
public class AITravelController {
    // 百炼平台的appid,本案例是智能体应用-AI-Travel
    @Value("${spring.ai.dashscope.agent.options.app-id}")
    private String Travel_APPID;

    // 百炼云端智能体调用对象
    private DashScopeAgent agent;

    //构造方法注入，创建百炼云端智能体对象
    public AITravelController(DashScopeAgentApi agentApi) {
        this.agent = new DashScopeAgent(agentApi);
    }


    /**
     * 普通输出用call方法
     * <p>
     * http://localhost:7024/travel
     *
     * @param msg
     * @return
     */
    @GetMapping("/travel")
    public String travel(@RequestParam(name = "msg", defaultValue = "明天去北京玩5天，" +
            "查询一下北京的天气并制定一个预算在8000元以内的放游计划") String msg) {

        DashScopeAgentOptions options = DashScopeAgentOptions.builder().withAppId(Travel_APPID).build();

        Prompt prompt = new Prompt(msg, options);

        return agent.call(prompt).getResult().getOutput().getText();
    }

    /**
     * 流式输出用stream方法
     *
     * @param msg
     * @return
     */
    @GetMapping("/travel2")
    public Flux<String> travel2(@RequestParam(name = "msg", defaultValue = "明天去北京玩5天，" +
            "查询一下北京的天气并制定一个预算在8000元以内的放游计划") String msg) {

        DashScopeAgentOptions options = DashScopeAgentOptions.builder().withAppId(Travel_APPID).build();
//        Prompt prompt = new PromptTemplate("以html格式输出").create(Map.of(
//                "msg", msg,
//                "output_format", "html",
//                "options", options
//        ));
//        prompt.getOptions(options);
        Prompt prompt = new Prompt(msg, options);


//        return agent.stream(prompt).map(chatResponse -> chatResponse.getResults().get(0).getOutput().getText());
        return agent.stream(prompt).map(chatResponse -> chatResponse.getResult().getOutput().getText());
    }

}
